package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 *
 * 通过Object的wait notify来进行同步控制
 * Created by gavin on 15-9-1.
 */
public class OrigenalProducerConsumer {
    public static void main(String[] args)
    {
        ExecutorService threadPool = new ThreadPoolExecutor(2,2,60000L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory());
        EventStorage eventSorage = new EventStorage();
        threadPool.execute(new Consumer(eventSorage));
        threadPool.execute(new Producer(eventSorage));
    }
}

class Consumer implements Runnable{
    private EventStorage eventStorage;

    public Consumer(EventStorage eventStorage) {
        this.eventStorage = eventStorage;
    }

    public void run() {
        while (true)
        {
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(eventStorage.get());

        }

    }
}

class Producer implements Runnable{
    private EventStorage eventStorage;

    public Producer(EventStorage eventStorage) {
        this.eventStorage = eventStorage;
    }

    public void run() {
        while (true)
        {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            eventStorage.add(Thread.currentThread().getName()+" "+ System.currentTimeMillis());
        }

    }
}

class EventStorage{
    private int max=5;
    private List<String> list = new ArrayList<String>();


    public synchronized void add(String str)
    {
        while (list.size() == 5)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(str);
        System.out.println("add one message");
        notify();
    }

    public synchronized String get()
    {
        while (list.size() == 0)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String str = list.remove(0);
        notify();
        return str;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
}
